package com.iniapp.app.jsf;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings("serial")
public class SecurityPhaseListener implements PhaseListener{

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Override
	public void afterPhase(PhaseEvent event) {
		FacesContext context = event.getFacesContext();
		String pathInfo = context.getExternalContext().getRequestServletPath();
		
		if(logger.isTraceEnabled()){
			logger.trace("current URL =  {}", pathInfo);
		}
		
		if(!JsfSecurityUtil.isIgnored(pathInfo)){
			Identity identity = null;
			try{
				identity = JsfSecurityUtil.getCurrentIdentity();
			}catch(Exception e){
				logger.error("Context is not active");
			}

			if(identity == null || !identity.isLoggedIn()){
				logger.warn("Please login first. ");
				JSFUtility.addWarn("Please login first.");
				context.getApplication().getNavigationHandler().handleNavigation(context, null, "notYetLogin");
			}else{
				
				logger.trace("Checking security authorization for: {}", pathInfo);
				logger.trace("Granted URLs/Actions: \n {} \n {}", identity.getGrantedUrls(), identity.getGrantedActions());
				if(!JsfSecurityUtil.isUrlMatch(pathInfo, identity.getGrantedUrls())){
					logger.warn("you don't have the right to access URL {}.", pathInfo);
					JSFUtility.addWarn("You don't have the right to access this URL.");
					context.getApplication().getNavigationHandler().handleNavigation(context, null, "accessDenied");					
				}else{
					logger.trace("You are granted to access URL {}", pathInfo);
				}
			}
		}

	}
	
	@Override
	public void beforePhase(PhaseEvent event) {
	
	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}

}
